package database

import (
	"fmt"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
)

// TransactionType 交易类型
type TransactionType string

// TransactionStatus 交易状态
type TransactionStatus string

const (
	// TransactionTypeMatrixTransfer 矩阵转账
	TransactionTypeMatrixTransfer TransactionType = "MATRIX_TRANSFER"
	// TransactionStatusCompleted 交易完成
	TransactionStatusCompleted TransactionStatus = "COMPLETED"
)

// Transaction 交易记录
type Transaction struct {
	TransactionID string            `json:"transaction_id"`
	CardID        string            `json:"card_id"`
	Type          TransactionType   `json:"type"`
	Amount        float64           `json:"amount"`
	Currency      string            `json:"currency"`
	Status        TransactionStatus `json:"status"`
	MatrixAccount string            `json:"matrix_account"`
	Platform      string            `json:"platform"`
	RawData       interface{}       `json:"raw_data"`
	CreatedAt     time.Time         `json:"created_at"`
	UpdatedAt     time.Time         `json:"updated_at"`
}

// RecordTransaction 记录交易
func RecordTransaction(
	prefix string,
	cardID string,
	transactionType TransactionType,
	amount float64,
	currency string,
	status TransactionStatus,
	matrixAccount string,
	platform string,
	rawData interface{},
) (*Transaction, error) {
	transaction := &Transaction{
		TransactionID: fmt.Sprintf("%s%d", prefix, time.Now().UnixNano()),
		CardID:        cardID,
		Type:          transactionType,
		Amount:        amount,
		Currency:      currency,
		Status:        status,
		MatrixAccount: matrixAccount,
		Platform:      platform,
		RawData:       rawData,
		CreatedAt:     time.Now(),
		UpdatedAt:     time.Now(),
	}

	if err := database.DB.Create(transaction).Error; err != nil {
		return nil, fmt.Errorf("failed to record transaction: %v", err)
	}

	return transaction, nil
}
